import { HttpClient, HttpHeaders } from '@angular/common/http';
import { CacheService } from '@core/routes-services/cache.service';
import { SERVER_DOMAIN } from '../../constant/config';
import { Observable } from 'rxjs';

export class BaseService {
  protected http: HttpClient;
  public cacheService: CacheService;

  constructor(http: HttpClient, cacheService: CacheService) {
    this.http = http;
    this.cacheService = cacheService;
  }

  /**
   * 构造并返回请求头
   * @returns {HttpHeaders}
   */
  getHeaders(): any {
    let headers = new HttpHeaders();
    headers.append('X-Requested-With', 'XMLHttpRequest');
    headers.append('Accept', 'application/json');
    headers.append('Content-Type', 'application/json; charset=UTF-8');
    const token: any = this.cacheService.getTokenInfo();
    if (token !== null) {
      headers = headers.append('Authorization',  token);
    }

    return { headers: headers, withCredentials: true, observe: 'response' };// observe: 'response' 定义返回整个response 而不仅仅是body ，各请求再根据后端返回结构做进一步处理
  }

  /**
   * get请求
   * @param url
   * @returns {Promise<T>|Promise<TResult|T>|Observable<R>|Promise<R>|any}
   */
  get(url): Promise<any> {
    return this.http.get(SERVER_DOMAIN + url, this.getHeaders())
      .toPromise()
      .then((res: any) => {
        if (res.ok) {
          return res.body || {};
        } else {// 结合后台返回数据格式 正常不应该到这里
          return res;
        }
      })
      .catch(this.handleError);
  }


  /**
   * post请求
   * @param url
   * @param body
   * @returns {Promise<T>|Promise<TResult|T>|Observable<R>|Promise<R>|any}
   */
  post(url, body): Promise<any> {
    return this.http.post(SERVER_DOMAIN + url, body, this.getHeaders())
      .toPromise()
      .then((res: any) => {
        if (url == 'auth/login') { // 登录接口成功返回特殊处理
          return res;
        } else {
          if (res.ok) {
            return res.body || {};
          } else {// 结合后台返回数据格式 正常不应该到这里
            return res;
          }
        }
      })
      .catch(this.handleError);
  }

  /**
   * delete请求
   * @param url
   * @param ids
   * @returns {Promise<*|{}>|Promise<T>|Promise<*|{}|T>|any<T>|Promise<R>|any}
   */
  delete(url, ids): Promise<any> {
    let deleteUrl = SERVER_DOMAIN + url;
    if (ids) {
      deleteUrl += ids;
    }

    return this.http.delete(deleteUrl, this.getHeaders())
      .toPromise()
      .then((res: any) => {
        if (res.ok) {
          return res.body || {};
        } else {// 结合后台返回数据格式 正常不应该到这里
          return res;
        }
      }).catch(this.handleError);
  }

  /**
   * put请求
   * @param url
   * @param body
   * @returns {Promise<T>|Promise<TResult|T>|Observable<R>|Promise<R>|any}
   */
  put(url, body?): Promise<any> {
    return this.http.put(SERVER_DOMAIN + url, body, this.getHeaders())
      .toPromise()
      .then((res: any) => {
        if (res.ok) {
          return res.body || {};
        } else {// 结合后台返回数据格式 正常不应该到这里
          return res;
        }
      })
      .catch(this.handleError);
  }

  /**
   * 错误处理
   * @param {Response | any} error
   * @returns {Promise<never>}
   */
  private handleError(error: Response | any) {
    if (error.status === 403 || error.error.status === 403) {
      window.location.href = "#/403"
      // return Promise.resolve("Sorry,You don't have permission.");
    }
    if (error.status === 401 || error.error.status ===401) {
      // 未登录，先登录
      window.location.href = '#/passport/login';
      // return Promise.resolve("Please sweep the qr code.");
    }
    // let errMsg = (error.error.message) ? error.error.message :
    //   error.status ? `${error.status} - ${error.statusText}` : 'Server error'
    return Promise.reject(error.error);
  }
}
